package com.example.module.user.login

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.didi.drouter.api.DRouter
import com.example.common.sdk.base.BaseActivity
import com.example.common.sdk.extend.observerWithResult
import com.example.module.user.databinding.UserActivityLoginBinding
import com.example.module.user.login.vm.LoginViewModel
import com.example.module.user.register.RegisterActivity

class LoginActivity : BaseActivity(), View.OnClickListener {


    private lateinit var mBinding: UserActivityLoginBinding
    private lateinit var modelLogin: LoginViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = UserActivityLoginBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.btnLogin.setOnClickListener(this)
        mBinding.tvGoRegister.setOnClickListener(this)

        modelLogin = ViewModelProvider(this)[LoginViewModel::class.java]
        modelLogin.onToastResult.observe(this, Observer {
            toast(it)
        })

        modelLogin.onLoginResult.observerWithResult(this, this, true, onSuccess = {
            toast("登录成功")
            DRouter.build("/main/home").start()
        })


        mBinding.etUserName.setText(modelLogin.getCacheUserName())
        mBinding.etPassword.setText(modelLogin.getCachePassword())
    }

    override fun onClick(v: View) {
        if (v == mBinding.btnLogin) {
            val userName = mBinding.etUserName.text.toString()
            val password = mBinding.etPassword.text.toString()
            modelLogin.login(userName, password)
        } else if (v == mBinding.tvGoRegister) {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }
}